#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
FlaSam Code

2007 2007-6-26 上午11:24:25
'''
# Create your views here.

from ad_decorators import *
from ad_validations import *
from apps.ad_usergroup.models import AdAgentInfo
from apps.ad_usergroup.models import AdClientInfo
from apps.ad_usergroup.models import AdManagerInfo
from apps.ad_usergroup.models import AdPlace
from apps.ad_usergroup.models import AdPlayerInfo
from apps.ad_usergroup.models import AdUserProfile
from apps.ad_usergroup.models import get_group_members
from django import newforms as forms
from django.conf import settings
from django.contrib.auth import logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core import validators
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.newforms import form_for_fields, form_for_model, form_for_instance
from django.newforms.extras import SelectDateWidget
from django.template import Context, Template, loader, RequestContext
from django.views.generic.create_update import update_object, create_object, delete_object
from django.views.generic.list_detail import object_list, object_detail
import datetime

def flash(request, msg, tit):
    '''
    touch request session , show post message to user
    @param request:
    @param msg:
    @param tit:
    '''
    request.session['flash_msg'] = msg
    request.session['flash_params'] = {'type': tit}
    return 
    
def check_user_obj_is_super_admin(user_obj):
    '''
    check input user obj is super admin
    @param user_obj:
    '''
    if user_obj.username in settings.AD_SUPER_ADMIN:
        return True
    else:
        return False

def check_current_user_is_super_admin(request):
    '''
    check current login user is super admin
    @param request:
    '''
    if str(request.user) in settings.AD_SUPER_ADMIN:
        return True
    else:
        return False
    
def super_admin_protect(request, user_object):
    '''
    check current and user object is super admin
    @param request:
    @param user_object:
    '''
    if check_user_obj_is_super_admin(user_object):
        if check_current_user_is_super_admin(request):
            return True
        else:
            return False
    else:
        return True
    
def creator_protect(request, o):
    '''
    check input obj is current user create or is obj's manager 
    @param request:
    '''
    
    if request.username == o.creator.username:
        return True
    else:
        return False

@login_required
def index(request):
    
    if request.user.is_authenticated():
        return HttpResponse('OKOK', 'text/html')
    else:
        return HttpResponseRedirect('/accounts/login')
    
def logout(request):
    '''
    user logout
    @param request:
    '''
    logout(request)
    # Redirect to a account login page.

@check_role('corp_managers')
def users_list(request):
    
    user_list_qs = User.objects.all().order_by('id')
    
    return object_list(request, queryset=user_list_qs, template_name='user_list.html', paginate_by=15)

@check_role('corp_managers')
def users_detail(request, i):
    '''
    #TODO: should add a test , to check current view user's manager is current login user
    @param request:
    @param i:
    '''
    # get user obj
    u_obj = User.objects.get(id=i)
    
    # get userprofile obj
    try:
        up_obj = AdUserProfile.objects.get(user=u_obj)
    except AdUserProfile.DoesNotExist: #@UndefinedVariable
        # oops not find userprifile in my database, auto create it and set default value
        up_obj = AdUserProfile(
                              user=u_obj, \
                              user_desc='System auto add userprofile at: %s' % datetime.datetime(2007, 2, 2).now(), \
                              user_expire_date=datetime.datetime(2007, 2, 2).now().date(), \
                              user_place = AdPlace.objects.get(place_name__exact='中国') #@UndefinedVariable
                              )
        up_obj.save()
    
    # make user form
    UserForm = form_for_instance(u_obj, fields=['username', \
                                                      'email', \
                                                      'is_staff', \
                                                      'is_active', \
                                                      'groups', \
                                                      'user_permissions', 
                                                      ])
    # make user profile form
    UserProfileForm = form_for_instance(up_obj, fields=['user_type', \
                                                                'user_phone', \
                                                                    'user_desc', \
                                                                    'user_place', \
                                                                    'user_expire_date', \
                                                                    ])
    
    
    #UserProfileForm.base_fields['user_expire_date'].widget = SelectDateWidget()
    #print up_obj.user_expire_date
    #UserProfileForm(initial={'user_expire_date':up_obj.user_expire_date})

    if super_admin_protect(request, u_obj):
        pass
    else:
        return HttpResponseRedirect('/error_permission')
    
#===============================================================================
#    now process real request
#===============================================================================
    # check http request method
    if request.method == 'GET':# just show info
        e_c = {
               'userform': UserForm(), \
               'userprofileform': UserProfileForm
               }
        return update_object(request, model=AdUserProfile, object_id=i, template_name='user_detail.html', extra_context=e_c)
    
    elif request.method == 'POST': # do post , update user info
        # bind user request post input data
        u = UserForm(request.POST)
        up = UserProfileForm(request.POST)
        
        # test all form are valid
        if u.is_valid() and up.is_valid():
            
            # OK save all data into database 
            u.save()
            up.save()
            
            # Now add default account profile info obj
            # get current create user's obj
            current_u_obj = User.objects.get(username=str(request.user))
            # by default , user place is china
            place_obj = AdPlace.objects.get(place_name__exact='中国') #@UndefinedVariable

            if str(request['user_type']) == 'manager':
                print 'user type is manager'
                manager_info_obj = AdManagerInfo(username=u_obj, \
                                         user_cname='请填写', \
                                         user_phone='12345678', \
                                         user_mophone='12345678', \
                                         user_dept='未知')
                try:
                    manager_info_obj.save()
                except: #@UndefinedVariable
                    pass
            elif str(request['user_type']) == 'agent':
                print 'user type is agent'
                agent_info_obj = AdAgentInfo(username=u_obj, \
                                             #manager=current_u_obj, \
                                             user_corp_name='未知', \
                                             user_corp_place=place_obj, \
                                             user_corp_address='未知', \
                                             user_position='未知', \
                                             user_cname='未知', \
                                             user_phone='12345678', \
                                             user_mophone='12345678'
                                             )

                agent_info_obj.save()
            elif str(request['user_type']) == 'client':
                print 'user type is client'
                client_info_obj = AdClientInfo(username=u_obj, \
                                               #manager=current_u_obj, \
                                               user_position='未知', \
                                               user_cname='请填写', \
                                               user_phone='12345678', \
                                               user_mophone='12345678', \
                                               user_corp_name='未知', \
                                               user_corp_place=place_obj, \
                                               user_corp_address='未知'
                                               )
                try:
                    client_info_obj.save()
                except:
                    pass
            elif str(request['user_type']) == 'player':
                print 'user type is player'
                player_info_obj = AdPlayerInfo(username=u_obj, \
                                               #manager=current_u_obj, \
                                               user_position='未知', \
                                               user_cname='请填写', \
                                               user_phone='12345678', \
                                               user_mophone='12345678', \
                                               user_corp_name='未知', \
                                               user_corp_place=place_obj, \
                                               user_corp_level=0, \
                                               user_corp_terminal_amount=0, \
                                               user_corp_address='未知'
                                               )
                try:
                    player_info_obj.save()
                except:
                    pass
            else:
                pass
            # when all finished redirect to user info page
            flash(request, '用户信息已经被成功保存', 'Ok')

            return HttpResponseRedirect("/users/%s/" % i)
        # maybe not valid , show error
        else:
            e_c = {
               'userform': u, \
               'userprofileform': up
               }
            flash(request, '请仔细检查表单,填写正确信息', 'Error')
            return update_object(request, model=User, object_id=i, template_name='user_detail.html', extra_context=e_c, post_save_redirect="/users/%(slug)s/")

@check_role('corp_managers')
def users_create(request):
    
    UserForm = form_for_model(User, fields=['username', \
                                                      'email', \
                                                      #'is_staff', \
                                                      'is_active', \
                                                      'groups', \
                                                      'user_permissions', 
                                                      ])
    
    if request.method == 'GET':
        u = UserForm()
        e_c = {
               'userform': u, \
               }
        
        return create_object(request, model=User, template_name='user_create.html', extra_context=e_c, post_save_redirect='/users/')
    elif request.method == 'POST':
        u = UserForm(request.POST) 
        
        if u.is_valid() :
            try:
                u.save()
            except:
                flash(request, '用户信息信息错误请重新填写', 'Error')
                return HttpResponseRedirect('/users/add/')
            
            u_obj = User.objects.get(username__exact=request['username'])

            flash(request, '请继续填写用户的详细信息', 'Ok')
            
            # at first , I will add base user info , then redirect to full user info update page
            return HttpResponseRedirect('/users/%d/' % u_obj.id)
        else:
            e_c = {
                   'userform': u, \
                 }
            return create_object(request, model=User, template_name='user_create.html', extra_context=e_c, post_save_redirect='/users/')
    else:
        pass

@check_role('corp_managers')
def users_change_state(request, i):
    
    u_obj = User.objects.get(id=i)

    if super_admin_protect(request, u_obj):
        pass
    else:
        return HttpResponseRedirect('/error_permission')
    
    # OK change user state
    if u_obj.is_active == True:
        u_obj.is_active = False
    elif u_obj.is_active == False:
        u_obj.is_active = True
        
    u_obj.save()
    
    return HttpResponseRedirect('/users/')

class UserPassForm(forms.Form):
    
    u_id = forms.IntegerField(widget=forms.HiddenInput)
    p1 = forms.CharField(required=True, min_length=6, label=u'输入密码', widget=forms.PasswordInput)
    p2 = forms.CharField(required=True, min_length=6, label=u'确认密码', widget=forms.PasswordInput)
    
    def clean_p2(self):
        if self.data['p1'] and self.data['p2'] and self.data['p1'] != self.data['p2']:
            raise forms.ValidationError('新密码效验不一致')
    def save(self):
        
        u_obj = User.objects.get(id=self.data['u_id'])
        u_obj.set_password(self.data['p1'])
        u_obj.save()

@check_role('corp_administrators')
def users_change_passwd(request, i):
    '''
    Only administrator Group can be change other user's password
    @param request:
    @param i:
    '''
    
    #user_pass_form = UserPassForm()

    try:
        u_obj = User.objects.get(id=i)
    except User.DoesNotExist: #@UndefinedVariable
        return Http404

    if super_admin_protect(request, u_obj):
        pass
    else:
        return HttpResponseRedirect('/error_permission')
    
    t = loader.get_template('user_change_pass.html')    
    
    if request.method == 'POST':
        u = UserPassForm(request.POST)
        c = Context({
                     'request':request, \
                     'user':u_obj, \
                     'form':u
                     })
        if u.is_valid():
            u.save()
            flash(request, '用户密码修改成功', 'Ok')
            return HttpResponse(t.render(c))
        else:
            flash(request, '修改密码错误', 'Error')
            return HttpResponse(t.render(c))
        
    elif request.method == 'GET':
        user_pass_form = UserPassForm(initial={'u_id':i})
        c = Context(
                {'user':u_obj, \
                 'form':user_pass_form, \
                 'request': request
                 }
                )
        return HttpResponse(t.render(c))
    else:
        return HttpResponse('Oops !!!', 'text/html')
    
@check_role('corp_administrators')
def users_delete(request, i):
    '''
    Only administrator group can be delete user
    @param request:
    @param i:
    '''
    try:
        u_obj = User.objects.get(id=i)

        if super_admin_protect(request, u_obj):
            pass
        else:
            return HttpResponseRedirect('/error_permission')
    
        u_obj.delete()
    except User.DoesNotExist: #@UndefinedVariable
        pass
    
    try:
        up_obj = AdUserProfile.objects.get(username=u_obj)
        up_obj.delete()
    except AdUserProfile.DoesNotExist: #@UndefinedVariable
        pass
    
    return HttpResponseRedirect('/users/')
        

@check_role('corp_managers')
def group_list(request):
    
    group_list_qs = Group.objects.all().order_by('id')

    return object_list(request, queryset=group_list_qs, template_name='group_list.html')
    
    
@check_role('corp_managers')
def group_detail(request, i):
        
    group_detail_obj = Group.objects.all()
    g_m = get_group_members(i)
    e_c = {
           'group_members':g_m
           }
    return object_detail(request, \
                         queryset=group_detail_obj, \
                         object_id=i, \
                         extra_context=e_c, \
                         template_name='group_detail.html'
                         )

def account_manager_type_detail(request, user_obj, userprofile_obj, editable=False, return_code=False):
    '''
        if user_type is manager , then show manager info 
    @param request: http request
    @param user_obj:
    @param userprofile_obj:
    @param editable: if true allow user to edit it , else user user can view 
    @param return_code:
    '''
    
    manager_info_obj = AdManagerInfo.objects.get(username=user_obj) #@UndefinedVariable
        
    manager_info_obj_all = AdManagerInfo.objects.all() #@UndefinedVariable
    
    manager_info_form = form_for_instance(manager_info_obj, fields=['user_dept', \
                                                                            'user_position', \
                                                                            'user_cname', \
                                                                            'user_phone', \
                                                                            'user_mophone', \
                                                                            ])
    if editable:
        if request.method == 'GET':
          
            if super_admin_protect(request, user_obj):
                pass
            else:
                return HttpResponseRedirect('/error_permission')
    
            
            e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': manager_info_form()
                   }
            return update_object(request, model=AdManagerInfo, object_id=manager_info_obj, template_name='account_detail_update.html', extra_context=e_c)
        elif request.method == 'POST':

            if super_admin_protect(request, user_obj):
                pass
            else:
                return HttpResponseRedirect('/error_permission')
            
            u = manager_info_form(request.POST)
            
            if u.is_valid():
                u.save()
                e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': u
                   }
                flash(request, '用户信息修改成功', 'Ok')
                return update_object(request, post_save_redirect='/users/', model=AdManagerInfo, object_id=manager_info_obj, template_name='account_detail_update.html', extra_context=e_c)
                
            else:
                e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': u
                   }
                flash(request, '用户信息修改失败', 'Error')
                return update_object(request, model=AdManagerInfo, object_id=user_obj, template_name='account_detail_update.html', extra_context=e_c)
        
        else:
            return Http404
    else:
        e_c = {
               'user_obj': user_obj, \
               'userprofile_obj': userprofile_obj
               }
        return object_detail(request, \
                             queryset=manager_info_obj_all, \
                             object_id=manager_info_obj, \
                             extra_context=e_c, \
                             template_name='account_manager_detail_view.html')
        
def account_agent_type_detail(request, user_obj, userprofile_obj, editable=False, return_code=False):
    '''
        if user_type is agent , then show manager info 
    @param request: http request
    @param user_obj:
    @param userprofile_obj:
    @param editable: if true allow user to edit it , else user user can view 
    @param return_code:
    '''
    
    agent_info_obj = AdAgentInfo.objects.get(username=user_obj) #@UndefinedVariable
        
    agent_info_obj_all = AdAgentInfo.objects.all() #@UndefinedVariable
    
    agent_info_form = form_for_instance(agent_info_obj, fields=['user_corp_name', \
                                                                'user_corp_place', \
                                                                'user_corp_address', \
                                                                            'user_position', \
                                                                            'user_cname', \
                                                                            'user_phone', \
                                                                            'user_mophone', \
                                                                            ])
    
    if editable:
        if request.method == 'GET':          

            if super_admin_protect(request, user_obj):
                pass
            else:
                return HttpResponseRedirect('/error_permission')
            
            e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': agent_info_form()
                   }
            
            return update_object(request, model=AdAgentInfo, object_id=agent_info_obj, template_name='account_detail_update.html', extra_context=e_c)
        elif request.method == 'POST':
            if super_admin_protect(request, user_obj):
                pass
            else:
                return HttpResponseRedirect('/error_permission')
            
            u = agent_info_form(request.POST)
            
            if u.is_valid():
                u.save()
                e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': u
                   }
                flash(request, '用户信息修改成功', 'Ok')
                return update_object(request, model=AdAgentInfo, post_save_redirect='/users/', object_id=agent_info_obj, template_name='account_detail_update.html', extra_context=e_c)
                
            else:
                e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': u
                   }
                flash(request, '用户信息修改失败', 'Error')
                return update_object(request, model=AdAgentInfo, object_id=user_obj, template_name='account_detail_update.html', extra_context=e_c)
        
        else:
            return Http404
    else:
        e_c = {
               'user_obj': user_obj, \
               'userprofile_obj': userprofile_obj
               }
        return object_detail(request, \
                             queryset=agent_info_obj_all, \
                             object_id=agent_info_obj, \
                             extra_context=e_c, \
                             template_name='account_agent_detail_view.html')
        
def account_client_type_detail(request, user_obj, userprofile_obj, editable=False, return_code=False):
    '''
        if user_type is agent , then show manager info 
    @param request: http request
    @param user_obj:
    @param userprofile_obj:
    @param editable: if true allow user to edit it , else user user can view 
    @param return_code:
    '''
    
    client_info_obj = AdClientInfo.objects.get(username=user_obj) #@UndefinedVariable
        
    client_info_obj_all = AdClientInfo.objects.all() #@UndefinedVariable
    
    client_info_form = form_for_instance(client_info_obj, fields=['user_corp_name', \
                                                                'user_corp_place', \
                                                                'user_corp_address', \
                                                                            'user_position', \
                                                                            'user_cname', \
                                                                            'user_phone', \
                                                                            'user_mophone', \
                                                                            ])
    
    if editable:
        if request.method == 'GET':   
            if super_admin_protect(request, user_obj):
                pass
            else:
                return HttpResponseRedirect('/error_permission')
            
            e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': client_info_form()
                   }
            
            return update_object(request, model=AdClientInfo, object_id=client_info_obj, template_name='account_detail_update.html', extra_context=e_c)
        elif request.method == 'POST':

            if super_admin_protect(request, user_obj):
                pass
            else:
                return HttpResponseRedirect('/error_permission')
            
            u = client_info_form(request.POST)
            
            if u.is_valid():
                u.save()
                e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': u
                   }
                flash(request, '用户信息修改成功', 'Ok')
                return update_object(request, model=AdClientInfo, post_save_redirect='/users/', object_id=client_info_obj, template_name='account_detail_update.html', extra_context=e_c)
                
            else:
                e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': u
                   }
                flash(request, '用户信息修改失败', 'Error')
                return update_object(request, model=AdClientInfo, object_id=user_obj, template_name='account_detail_update.html', extra_context=e_c)
        
        else:
            return Http404
    else:
        e_c = {
               'user_obj': user_obj, \
               'userprofile_obj': userprofile_obj
               }
        return object_detail(request, \
                             queryset=client_info_obj_all, \
                             object_id=client_info_obj, \
                             extra_context=e_c, \
                             template_name='account_client_detail_view.html')
        
def account_player_type_detail(request, user_obj, userprofile_obj, editable=False, return_code=False):
    '''
        if user_type is agent , then show manager info 
    @param request: http request
    @param user_obj:
    @param userprofile_obj:
    @param editable: if true allow user to edit it , else user user can view 
    @param return_code:
    '''
    
    player_info_obj = AdPlayerInfo.objects.get(username=user_obj) #@UndefinedVariable
        
    player_info_obj_all = AdPlayerInfo.objects.all() #@UndefinedVariable
    
    player_info_form = form_for_instance(player_info_obj, fields=['user_corp_name', \
                                                                'user_corp_place', \
                                                                'user_corp_address', \
                                                                            'user_position', \
                                                                            'user_cname', \
                                                                            'user_phone', \
                                                                            'user_mophone', \
                                                                            'user_corp_level', \
                                                                            'user_corp_terminal_amount'
                                                                            ])
    
    if editable:
        if request.method == 'GET':           

            if super_admin_protect(request, user_obj):
                pass
            else:
                return HttpResponseRedirect('/error_permission')
            
            e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': player_info_form()
                   }
            
            return update_object(request, model=AdPlayerInfo, object_id=player_info_obj, template_name='account_detail_update.html', extra_context=e_c)
        elif request.method == 'POST':
            
            if super_admin_protect(request, user_obj):
                pass
            else:
                return HttpResponseRedirect('/error_permission')
            
            u = player_info_form(request.POST)
            
            if u.is_valid():
                u.save()
                e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': u
                   }
                flash(request, '用户信息修改成功', 'Ok')
                return update_object(request, model=AdPlayerInfo, post_save_redirect='/users/', object_id=player_info_obj, template_name='account_detail_update.html', extra_context=e_c)
                
            else:
                e_c = {
                   'user_obj': user_obj, \
                   'userprofile_obj': userprofile_obj, \
                   'accountsform': u
                   }
                flash(request, '用户信息修改失败', 'Error')
                return update_object(request, model=AdPlayerInfo, object_id=user_obj, template_name='account_detail_update.html', extra_context=e_c)
        
        else:
            return Http404
    else:
        e_c = {
               'user_obj': user_obj, \
               'userprofile_obj': userprofile_obj
               }
        return object_detail(request, \
                             queryset=player_info_obj_all, \
                             object_id=player_info_obj, \
                             extra_context=e_c, \
                             template_name='account_player_detail_view.html')

@login_required
def accounts_profile_deatil_user_himself(request):
    '''
    user account info selfservice view 
    @param request:
    '''
    print request.user
    
    u_obj = User.objects.get(username=str(request.user))
    
    up_obj = u_obj.get_profile()
    
    u_type = up_obj.user_type
    
    if u_type == 'manager':
        return account_manager_type_detail(request, u_obj, up_obj, editable=True)
    elif u_type == 'agent':
        return account_agent_type_detail(request, u_obj, up_obj, editable=True)
    elif u_type == 'player':
        return account_player_type_detail(request, u_obj, up_obj, editable=True)
    elif u_type == 'client':
        return account_client_type_detail(request, u_obj, up_obj, editable=True)
    else:
        return HttpResponse('Oops!!!', 'text/html')
    
    return HttpResponse('account profile', 'text/html')

@check_role('corp_managers')
def accounts_profile_detail_admin_update(request, i):
    '''
    admin update account profile info, 
    @param request:
    @param i: i is user id , not account tab id
    '''
    
    u_obj = User.objects.get(id=i)
    
    up_obj = u_obj.get_profile()
    
    u_type = up_obj.user_type
    
    if u_type == 'manager':
        return account_manager_type_detail(request=request, user_obj=u_obj, userprofile_obj=up_obj, editable=True)
            
    elif u_type == 'agent':
        return account_agent_type_detail(request=request, user_obj=u_obj, userprofile_obj=up_obj, editable=True)
    
    elif u_type == 'client':
        return account_client_type_detail(request=request, user_obj=u_obj, userprofile_obj=up_obj, editable=True)
    
    elif u_type == 'player':
        return account_player_type_detail(request=request, user_obj=u_obj, userprofile_obj=up_obj, editable=True)
    
    return HttpResponse('OK admin update account profile info', 'text/html')

def accounts_profile_detail_admin_view(request, i):
    u_obj = User.objects.get(id=i)
    
    up_obj = u_obj.get_profile()
    
    u_type = up_obj.user_type
    
    if u_type == 'manager':
        return account_manager_type_detail(request=request, user_obj=u_obj, userprofile_obj=up_obj, editable=False)
            
    elif u_type == 'agent':
        return account_agent_type_detail(request=request, user_obj=u_obj, userprofile_obj=up_obj, editable=False)
    
    elif u_type == 'client':
        return account_client_type_detail(request=request, user_obj=u_obj, userprofile_obj=up_obj, editable=False)
    
    elif u_type == 'player':
        return account_player_type_detail(request=request, user_obj=u_obj, userprofile_obj=up_obj, editable=False)
    
    return HttpResponse('OK admin view account profile info', 'text/html')

#class AccountsPassForm(forms.Form):
#    
#    #u_id = forms.IntegerField(widget=forms.HiddenInput)
#    old_pass = forms.CharField(required=True, min_length=6, label=u'输入原密码', widget=forms.PasswordInput)
#    p1 = forms.CharField(required=True, min_length=6, label=u'输入新密码', widget=forms.PasswordInput)
#    p2 = forms.CharField(required=True, min_length=6, label=u'再次输入新密码', widget=forms.PasswordInput)
#
#    def save(self):
#        pass
    
class AccountsPassForm(forms.Form):
    oldpassword = forms.CharField(widget=forms.PasswordInput(), label='原始密码')
    password1 = forms.CharField(widget=forms.PasswordInput(), min_length=6, label='新密码')
    password2 = forms.CharField(widget=forms.PasswordInput(), min_length=6, label='密码确认')

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(AccountsPassForm, self).__init__(*args, **kwargs)

    def clean_oldpassword(self):
        
        print self.data, 'form data'
        if self.data['oldpassword'] and not self.user.check_password(self.data['oldpassword']):
            raise forms.ValidationError('输入正确的原始密码')
        return self.data['oldpassword']

    def clean_password2(self):
        if self.data['password1'] and self.data['password2'] and self.data['password1'] != self.data['password2']:
            raise forms.ValidationError('新密码效验不一致')
        return self.data['password2']
    
    def save(self):
        self.user.set_password(self.data['password2'])
        self.user.save()

@login_required
def accounts_change_passwd_himself(request):
    
    # get current login user's User Object
    u_obj = User.objects.get(username__exact=str(request.user))
    t = loader.get_template('accounts_change_pass.html')
    
    if request.method == 'GET':
        
        u = AccountsPassForm(request.user)
        c = Context({
                     'user': u_obj, \
                     'form':u, \
                     'request':request
                     })
        
        
        return HttpResponse(t.render(c))
    elif request.method == 'POST':
        u = AccountsPassForm(request.user, request.POST)
        c = Context({
                     'request':request, \
                     'user': u_obj, \
                     'form':u
                     })
        if u.is_valid():
            u.save()
            flash(request, '密码修改成功', 'Ok')
            return HttpResponse(t.render(c))
        else:
            flash(request, '密码修改失败', 'Error')
            return HttpResponse(t.render(c))

@check_role('corp_managers')
def place_list(request):
    
    all_place_obj = AdPlace.objects.all() #@UndefinedVariable
    
    e_c = {
           }
    
    return object_list(request, queryset=all_place_obj, template_name='place_list.html', extra_context=e_c, paginate_by=30)

def place_map(request):
    
    t = loader.get_template('place_map.html')
    c = Context({})
    
    return HttpResponse(t.render(c))

@check_role('corp_managers')
def place_parent_list(request, i):

    all_place_obj = AdPlace.objects.all() #@UndefinedVariable
    if i == 'None':
        place_obj = all_place_obj.filter(place_parent__isnull=True) #@UndefinedVariable
        e_c = {
               'parent_name' :'TOP PLACE'
           }
    
        return object_list(request, queryset=place_obj, template_name='place_parent_list.html', extra_context=e_c, paginate_by=32)
    else:
        parent_obj = AdPlace.objects.get(id=i) #@UndefinedVariable
        place_obj = all_place_obj.filter(place_parent__exact=parent_obj) #@UndefinedVariable
        e_c = {
               'parent_name':parent_obj.place_name
           }
    
        return object_list(request, queryset=place_obj, template_name='place_parent_list.html', extra_context=e_c, paginate_by=32)
    return HttpResponse('ad', 'text/html')

@check_role('corp_managers')
def place_detail(request, i):
    
    all_place_obj = AdPlace.objects.all() #@UndefinedVariable
    place_obj = AdPlace.objects.get(id=i) #@UndefinedVariable
    
    place_form = form_for_instance(place_obj)
    
    if request.method == 'GET':
        e_c = {
           'place_form': place_form
           }
        return object_detail(request, queryset=all_place_obj, object_id=i, template_name='place_detail.html', extra_context=e_c)
    elif request.method == 'POST':
        u = place_form(request.POST)
        if u.is_valid():
            try:
                u.save()
                flash(request, '修改成功', 'Ok')
            except validators.ValidationError:
                flash(request, '修改失败, 不能将自身作为地区父类', 'Error')
            e_c = {
               'place_form': u
               }
            return object_detail(request, queryset=all_place_obj, object_id=i, template_name='place_detail.html', extra_context=e_c)
        else:
            e_c = {
           'place_form': place_form
           }
            flash(request, '修改失败,检查栏目字符的正确性', 'Error')
            return object_detail(request, queryset=all_place_obj, object_id=i, template_name='place_detail.html', extra_context=e_c)
    else:
        pass
    
@check_role('corp_managers')
def place_delete(request, i):
    place_obj = AdPlace.objects.get(id=i) #@UndefinedVariable
    place_obj.aduserprofile_set.clear()
    flash(request, '删除地区成功. 注意!!!在本页面不能够完全删除该地区,只是断开所有关联到本地区的表联接', 'Ok')
    return HttpResponseRedirect('/place/')

@check_role('corp_managers')
def place_create(request):
    place_form = form_for_model(AdPlace)
    
    t = loader.get_template('place_create.html')
    
    if request.method == 'GET':
        
        c = Context({
                     'place_form':place_form(), \
                     'request':request
                     })
        return HttpResponse(t.render(c), 'text/html')
    elif request.method == 'POST':
        u = place_form(request.POST)
        if u.is_valid():
            u.save()
            c = Context({
                         'place_form':u , \
                         'request':request
                         })
            flash(request, '区域地点添加成功', 'Ok')
            return HttpResponse(t.render(c), 'text/html')
        else:
            c = Context({
                     'place_form':place_form(), \
                     'request':request
                     })
            flash(request, '添加错误,请重新填写', 'Error')
            return HttpResponse(t.render(c), 'text/html')
    else:
        pass
    



